﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Ec_System.WebUI.Models;
using Ec_System.Facade.Web;
using Ec_System.Models.Web;
using Webdiyer.WebControls.Mvc;
using Microsoft.Security.Application;
using Ec_System.API;

namespace Ec_System.WebUI.Areas.Web.Controllers
{
    [BasicAuth]
    public class UserCenterController : Controller
    {
        LoginViewModel userLoginInfo = new UserHelp().TryGetUserInfo();
        EvaluationFacade evaluationFacade = new EvaluationFacade();
        CustomerFacade customerFacade = new CustomerFacade();
        ItemOrderFacade itemOrderFacade = new ItemOrderFacade();
        CustomerComplaintFacade customerComplaintFacade = new CustomerComplaintFacade();
        CustomerAddressFacade customerAddressFacade = new CustomerAddressFacade();
        // GET: Web/UserCenter

        public ActionResult Index(string view)
        {
            ViewData["view"] = view;
            var model = new CustomerFacade().GetUserInfoAndOrderInfoByLoginID(userLoginInfo.LoginID);

            return View(model);
        }

        /// <summary>
        /// 查看订单页
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult GetOrderByLogin(int id = 1)
        {
            //if (userLoginInfo == null || !Request.IsAuthenticated)
            //{
            //    return RedirectToAction("UserLogin", "Customer", new { area = "Web" });
            //}
          
            ItemOrderRequestData request = new ItemOrderRequestData()
            {
                loginID = userLoginInfo.LoginID,
                PageIndex = id,
                PageSize = 4
            };

            var result = itemOrderFacade.GetOrderListWithPageByLoginID(request);
            var model = new PagedList<ItemOrderData>(result.Result, result.PageIndex, result.PageSize, result.TotalCount);
            ViewData["view"] = "userOrderList";
            return View("Index", model);
        }

        /// <summary>
        /// 申请退货
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="orderDetailsID"></param>
        /// <param name="vendorNumber"></param>
        /// <param name="reason"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ApplyReturnOrder(string orderId, string orderDetailsID, string vendorNumber, string reason)
        {
            var i = itemOrderFacade.ReturnOrder(orderId, orderDetailsID, vendorNumber, reason);
            if(i > 0)
            {
                return Json(new { ResultBool = true }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new { ResultBool = false }, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 用户评价商品页
        /// </summary>
        /// <param name="orderID"></param>
        /// <param name="productID"></param>
        /// <returns></returns>
        public ActionResult UserEvaluation(string orderID, string productID)
        {
            var model = itemOrderFacade.GetOrderInfoByOrderIDAndProductID(orderID, productID);

            //如果获取到数据为空, 则重定向到GetOrderByLogin页
            if(model == null || model.ItemDatailsList[0] == null)
            {
                return RedirectToAction("GetOrderByLogin", "UserCenter");
            }
            else
            {
                ViewData["view"] = "userEvaluation";
                return View("index", model);
            }
        }

        /// <summary>
        /// 添加评论API
        /// </summary>
        /// <param name="formCollection"></param>
        /// <returns></returns>
        public ActionResult CreateEvaluation(FormCollection formCollection)
        {
            EvaluationData model = new EvaluationData()
            {
                Contents = Sanitizer.GetSafeHtmlFragment(formCollection["txt_Content"]),
                InUser = userLoginInfo.LoginID,
                OrderDetailId = Sanitizer.GetSafeHtmlFragment(formCollection["hidOrderDetailID"]),
                OrderId = Sanitizer.GetSafeHtmlFragment(formCollection["hidOrderID"]),
                ProductID = int.Parse(Sanitizer.GetSafeHtmlFragment(formCollection["hidProductID"])),
                QualityStar = int.Parse(Sanitizer.GetSafeHtmlFragment(formCollection["rdo_Quality"])),
                ServiceStar = int.Parse(Sanitizer.GetSafeHtmlFragment(formCollection["rdo_Service"])),
                ShipStar = int.Parse(Sanitizer.GetSafeHtmlFragment(formCollection["rdo_Ship"])),
                VendorNumber = Sanitizer.GetSafeHtmlFragment(formCollection["hidVendor"])
            };
            
            var result = evaluationFacade.AddEvaluation(model);
            ViewData["view"] = "result";
            return View("Index");
        }

        /// <summary>
        /// 评论列表
        /// </summary>
        /// <param name="id">页码</param>
        /// <returns></returns>
        public ActionResult EvaluationList(int id = 1)
        {
            var request = new EvaluationRequestData()
            {
                PageIndex = id,
                PageSize = 5,
                LoginID = userLoginInfo.LoginID
            };
            var result = evaluationFacade.GetEvaluationListWithPage(request);
            var model = new PagedList<EvaluationData>(result.Result, request.PageIndex, request.PageSize, result.TotalCount);
            ViewData["view"] = "evaluationList";
            return View("Index", model);
        }


        /// <summary>
        /// 评论详情
        /// </summary>
        /// <param name="id">评论的ID</param>
        /// <returns></returns>
        public ActionResult EvaluationDetail(int id)
        {
            var model = evaluationFacade.GetEvaluationDetailByID(id);
            //防止用户恶意输入, 如果查询结果为空则重定向到评论列表
            if (model == null)
            {
                return RedirectToAction("EvaluationList", "UserCenter");
            }
            ViewData["view"] = "evaluationDetail";
            return View("Index", model);
        }

        /// <summary>
        /// 显示用户个人信息
        /// </summary>
        /// <returns></returns>
        public ActionResult ShowUserInfo()
        {           
            var model = customerFacade.GetUserInfoByLoginID(userLoginInfo.LoginID);
            ViewData["view"] = "editUserInfo";

            return View("Index", model);
        }

        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="formCollection"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult EditUserInfo(FormCollection formCollection)
        {
            CustomerFacade faca = new CustomerFacade();
            int year = int.Parse(Sanitizer.GetSafeHtmlFragment(formCollection["birthdayYear"]));
            int month = int.Parse(Sanitizer.GetSafeHtmlFragment(formCollection["birthdayMonth"]));
            int day = int.Parse(Sanitizer.GetSafeHtmlFragment(formCollection["birthdayDay"]));
            DateTime birthDay = new DateTime(year, month, day);
            CustomerData model = new CustomerData()
            {
                RealName = Sanitizer.GetSafeHtmlFragment(formCollection["txt_realname"]),
                Birthday = birthDay,
                Sex = Sanitizer.GetSafeHtmlFragment(formCollection["rdo_Sex"]),
                QQ = Sanitizer.GetSafeHtmlFragment(formCollection["txt_qq"]),
                Tel = Sanitizer.GetSafeHtmlFragment(formCollection["txt_tel"]),
                Email = Sanitizer.GetSafeHtmlFragment(formCollection["txt_mail"]),
                LoginID = userLoginInfo.LoginID
            };

            int result = customerFacade.UpdateUserInfoByLoginID(model);
            if(result <= 0)
            {
                ViewBag.CodeErr = "修改失败，请重新输入";
            }

            return RedirectToAction("ShowUserInfo", "UserCenter");          
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="formCollection"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult EditUserPassword(FormCollection formCollection)
        {
            string newPwd = Sanitizer.GetSafeHtmlFragment(formCollection["new_password"]);
            string oldPwd = Sanitizer.GetSafeHtmlFragment(formCollection["old_password"]);
            CustomerData model = new CustomerData()
            {
                Password = oldPwd,
                LoginID = userLoginInfo.LoginID
            };
            //验证密码
            var result = customerFacade.UserLoginValidate(model);
            if(result != null)
            {
                model.Password =newPwd;
                int i = customerFacade.UpdateUserPwdByLoginID(model);
                if(i > 0)
                {
                    TempData["Message"] = "修改密码成功";
                }
                else
                {
                    TempData["Message"] = "修改密码失败,请重新修改!";
                }              
            }
            else
            {
                TempData["Message"] = "密码错误";
            }

            return RedirectToAction("ShowUserInfo", "UserCenter");
        }

        /// <summary>
        /// 用户收货地址页
        /// </summary>
        /// <returns></returns>
        public ActionResult ShowUserAddress()
        {
            var model = customerAddressFacade.GetCustomerAdrListByLoginID(userLoginInfo.LoginID);
            ViewData["view"] = "userAdress";

            return View("Index", model);
        }

        /// <summary>
        /// 添加用户收货地址
        /// </summary>
        /// <param name="formCollection"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult AddCustomerAddress(FormCollection formCollection)
        {
            CustomerAdressData model = new CustomerAdressData()
            {
                Recever = Sanitizer.GetSafeHtmlFragment(formCollection["txt_recever"]),
                Province_ID =  Sanitizer.GetSafeHtmlFragment(formCollection["ddlProvince"]),
                City_ID = Sanitizer.GetSafeHtmlFragment(formCollection["ddlRegion"]),
                Town_ID = Sanitizer.GetSafeHtmlFragment(formCollection["ddlCounty"]),
                Zip = Sanitizer.GetSafeHtmlFragment(formCollection["txt_zip"]),
                PhoneNum = Sanitizer.GetSafeHtmlFragment(formCollection["txt_tel"]),
                TelNum = Sanitizer.GetSafeHtmlFragment(formCollection["txt_phone"]),
                AdressMain = Sanitizer.GetSafeHtmlFragment(formCollection["txt_addressMain"]),
                LoginID = userLoginInfo.LoginID
            };

            int result = customerAddressFacade.AddCustomerAdr(model);
            if(result <= 0)
            {
                TempData["Message"] = "添加失败";
            }

            return RedirectToAction("ShowUserAddress", "UserCenter");
        }

        /// <summary>
        /// 添加投诉页
        /// </summary>
        /// <param name="orderID"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult AddComplaint(string orderID)
        {
            ViewBag.OrderID = orderID;
            ViewData["view"] = "addComplaint";

            return View("Index");
        }
        [ValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult AddComplaint(FormCollection formCollection)
        {
            CustomerComplaintData model = new CustomerComplaintData()
            {
                CustomerLoginId = userLoginInfo.LoginID,
                OrderId = Sanitizer.GetSafeHtmlFragment(formCollection["txt_OrderId"]),
                ComplaintType = int.Parse(Sanitizer.GetSafeHtmlFragment(formCollection["com_ComplaintType"])),
                Title = Sanitizer.GetSafeHtmlFragment(formCollection["txt_Title"]),
                Contents = Sanitizer.GetSafeHtmlFragment(formCollection["txt_Content"])
            };

            int i  = customerComplaintFacade.AddComplaint(model);
            if(i >  0)
            {
                return RedirectToAction("ComplaintList");
            }
            else
            {
                ViewData["view"] = "addComplaint";
                TempData["ErrorMsg"] = "投诉添加失败";
                return View("Index");
            }
        }

        /// <summary>
        /// 投诉列表
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ComplaintList(int id = 1)
        {
            CustomerComplaintRequestData request = new CustomerComplaintRequestData()
            {
                PageIndex = id,
                PageSize = 5,
                LoginID = userLoginInfo.LoginID
            };
            var result = customerComplaintFacade.GetComplaintListWithPage(request);
            var model = new PagedList<CustomerComplaintData>(result.Result, request.PageIndex, request.PageSize, result.TotalCount);
            ViewData["view"] = "complaintList";

            return View("Index", model);
        }

        /// <summary>
        /// 投诉详情
        /// </summary>
        /// <param name="complaintID"></param>
        /// <returns></returns>
        public ActionResult ComplaintDetails(string complaintID)
        {
            var model = customerComplaintFacade.GetComplaintByID(complaintID);
            ViewData["view"] = "complaintDetails";
            return View("Index", model);
        }

        /// <summary>
        /// 继续投诉
        /// </summary>
        /// <param name="formCollection"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ContinueComplaint(FormCollection formCollection)
        {
            int complaintID = int.Parse(formCollection["hid_ID"]);
            ComplaintDetailData model = new ComplaintDetailData()
            {
                Contents = Sanitizer.GetSafeHtmlFragment(formCollection["txt_Content"]),
                ComplaintID =complaintID
            };

            customerComplaintFacade.AddComplaintDetail(model);

            return RedirectToAction("ComplaintDetails", "UserCenter", new { complaintID = complaintID.ToString() });
        }

    }
}